package com.xgz.entity;

import java.lang.reflect.Field;

public class Test2 {
    public static void main(String[] args) {
        //获取class对象
        //2.通过类的class属性获取
        Class<Animal> animalClass = Animal.class;
        //操作属性  设值 属性.set(对象，值)
        try {
            Animal animal = animalClass.newInstance();
/*            //对color属性进行设置
            Field color = animalClass.getField("color");
            color.set(animal,"黑色");
            //取值 属性.get(对象)
            Object o = color.get(animal);
            System.out.println("color的值： " + o);*/
            //获取所有的属性
            Field[] declaredFields = animalClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                //暴力反射
                declaredField.setAccessible(true);
                String typeName = declaredField.getGenericType().getTypeName();
                if (typeName.equals("java.lang.String")){
                    declaredField.set(animal,"字符串");
                }
                if (typeName.equals("java.lang.Integer")){
                    declaredField.set(animal,20);
                }
                Object o = declaredField.get(animal);
                System.out.println("属性名字是： " + declaredField + "，对应的值是：" + o);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
